<script setup lang="tsx">
import Write from './components/MyAccountSettingsWrite.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ref, unref } from 'vue'
import { useRoute } from 'vue-router'
import { useBaseDetailView } from '@/base/views/BaseDetailView'
import {
  sysAccountGetMyInfoApi,
  sysAccountUpdateMyInfoApi,
  sysAccountUpdatePasswordApi
} from '@/api/system/account/SysAccount'
import { SysAccountDetailVo, SysAccountEditQo } from '@/api/system/account/SysAccount/types'
import { ElButton, ElDialog, ElForm, ElFormItem, ElInput, ElMessage } from 'element-plus'
import { useUserStoreWithOut } from '@/store/modules/user'
import { rsaEncrypt } from '@/utils/RsaEncrypt'

const writeRef = ref<ComponentRef<typeof Write>>()
const detailView = useBaseDetailView<SysAccountDetailVo, SysAccountEditQo>(writeRef, 'SysAccount')
const { title, loading, currentRow, id, back } = detailView

const { query } = useRoute()
const editType = query.type as string

const save = async () => {
  loading.value = true
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    try {
      await sysAccountUpdateMyInfoApi(formData)
      ElMessage.success('保存成功')

      const res = await sysAccountGetMyInfoApi()
      const avatar = res.data.avatar
      const userInfo = useUserStoreWithOut().getUserInfo
      if (userInfo) {
        userInfo.avatar = avatar
        useUserStoreWithOut().setUserInfo(userInfo)
      }
    } catch (error) {
      console.error('保存失败', error)
    } finally {
      loading.value = false
    }
  } else {
    console.warn('无法获取请求表单')
    loading.value = false
  }
}

const loadDetail = async () => {
  const res = await sysAccountGetMyInfoApi()
  currentRow.value = res.data
}

const changePasswordDialogVisible = ref(false)
const openChangePasswordDialog = () => {
  changePasswordDialogVisible.value = true
  changePasswordForm.value = {
    originPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
}

const changePasswordRules = ref({
  originPassword: [
    {
      required: true,
      message: '请输入原密码',
      trigger: 'blur'
    }
  ],
  newPassword: [
    {
      required: true,
      message: '请输入新密码',
      trigger: 'blur'
    },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    {
      required: true,
      message: '请确认新密码',
      trigger: 'blur'
    },
    {
      // 比较原密码和新密码是否一致
      validator: (_, value, callback) => {
        if (value !== changePasswordForm.value.newPassword) {
          callback(new Error('新密码不一致'))
        } else {
          callback()
        }
      }
    }
  ]
})

const changePasswordForm = ref({
  originPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const changePasswordFormRef = ref<InstanceType<typeof ElForm>>()

const changePasswordLoading = ref(false)
const changePassword = async () => {
  changePasswordLoading.value = true
  const originPassword = rsaEncrypt(changePasswordForm.value.originPassword)
  const newPassword = rsaEncrypt(changePasswordForm.value.newPassword)
  const data = {
    originPassword,
    newPassword
  }
  try {
    await sysAccountUpdatePasswordApi(data)
    changePasswordDialogVisible.value = false
    ElMessage.success('修改密码成功')
  } finally {
    changePasswordLoading.value = false
  }
}

loadDetail()
</script>

<template>
  <ContentDetailWrap :title="title">
    <Write ref="writeRef" :current-row="currentRow" :edit-type="editType" :edit-id="id" />

    <template #header>
      <BaseButton @click="back">返回</BaseButton>
      <BaseButton type="primary" :loading="loading" @click="save" permission="'save'">
        保存
      </BaseButton>

      <BaseButton
        type="success"
        :loading="loading"
        @click="openChangePasswordDialog"
        permission="'changePassword'"
      >
        修改密码
      </BaseButton>
    </template>

    <el-dialog v-model="changePasswordDialogVisible" title="修改密码">
      <el-form
        ref="changePasswordFormRef"
        :model="changePasswordForm"
        :rules="changePasswordRules"
        label-width="200px"
      >
        <el-form-item label="请输入密码" prop="originPassword">
          <el-input
            v-model="changePasswordForm.originPassword"
            placeholder="请输入原密码"
            type="password"
            show-password
          />
        </el-form-item>

        <el-form-item label="请输入新密码" prop="newPassword">
          <el-input
            v-model="changePasswordForm.newPassword"
            placeholder="请输入密码"
            type="password"
            show-password
          />
        </el-form-item>
        <!--      再次输入密码-->
        <el-form-item label="请再次输入新密码" prop="confirmPassword" style="margin-top: 20px">
          <el-input
            v-model="changePasswordForm.confirmPassword"
            placeholder="请再次输入密码"
            type="password"
            show-password
          />
        </el-form-item>

        <div style="text-align: right; margin-top: 20px">
          <el-button type="primary" @click="changePassword" :loading="changePasswordLoading"
            >确定
          </el-button>
          <el-button
            type="default"
            @click="changePasswordDialogVisible = false"
            :loading="changePasswordLoading"
            >取消
          </el-button>
        </div>
      </el-form>
    </el-dialog>
  </ContentDetailWrap>
</template>
